/**  
* @Title: StockHistory.java 
* @Description:
* @Copyright: Copyright (c) 2018
* @Company:http://www.sinocon.cn
* @author: Su.Yuanlin  
* @date 2019年3月19日  
* @QQ 314078331  
* @Like 流水落花春去也，天上人间
*/
package com.mtons.mblog.quartz.task;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.jsoup.helper.StringUtil;

import com.mtons.mblog.modules.entity.StockHistory;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @Title: StockHistory
 * @Description:
 * @author:Su.Yuanlin
 * @date 2019年3月19日
 */
public class StockHistoryUtil {
	private static String stockHistoryUrl = "http://q.stock.sohu.com/hisHq?code=cn_{}&start={}&end={}&stat=1&order=D&period=d&callback=&rt=json";

	public static String getStockHistoryByTime(String begin, String end, String stockCode) {
		String url = cn.hutool.core.util.StrUtil.format(stockHistoryUrl, stockCode, begin, end);
		return HttpUtil.get(url);
	}

	public static List<StockHistory> getStockHistoryByJson(String json, String stockCode, String stockName) {
		if (StringUtil.isBlank(json))
			return null;

		List<StockHistory> entitys = new ArrayList<>();

		JSONArray objData = (JSONArray) JSONUtil.parse(json);

		if (ObjectUtil.isNotNull(objData)) {
			JSONArray history = (JSONArray) ((JSONObject) objData.get(0)).get("hq");

			if (ObjectUtil.isNull(history))
				return entitys;

			ListIterator<Object> listIterator = history.listIterator();

			while (listIterator.hasNext()) {
				JSONArray stockInfoJsonArray = (JSONArray) listIterator.next();

				StockHistory sh = new StockHistory();
				sh.setStockid(stockCode + stockInfoJsonArray.get(0));
				sh.setStockcode(stockCode);
				sh.setCreatetime(stockInfoJsonArray.getStr(0));
				sh.setUpdatetime(DateUtil.today());
				sh.setStockname(stockName);
				sh.setPrice(stockInfoJsonArray.getStr(2));
				sh.setQuarter(DateUtil.season(DateUtil.parse(stockInfoJsonArray.getStr(0))));
				
				entitys.add(sh);
			}
		}
		return entitys;

	}

	public static List<StockHistory> exec(String begin, String end, String stockCode, String stockName) {
		String json = getStockHistoryByTime(begin, end, stockCode);
		return getStockHistoryByJson(json, stockCode, stockName);
	}

	public static void main(String[] args) {
//		String json = getStockHistoryByTime("20180101", "20190318", "600776");
//		List<StockHistory> stockHistoryByJson = getStockHistoryByJson(json, "600776", "东方通信");
//		System.out.println(stockHistoryByJson);
		
		System.out.println(DateUtil.today().replaceAll("-", ""));
	}
}